/** 
 * @Description: GCJ02纠偏tiling
 * @Author: 程前
 * @Date: 2024-12-24 16:29:54
 * @LastEditors: 程前
 * @LastEditTime: 2024-12-24 16:38:37
 */
import {
  WebMercatorTilingScheme,
  WebMercatorProjection,
  Math as CesiumMath,
  Cartographic,
  Cartesian2,
  Ellipsoid
} from 'cesium'

import CoordTransform from './CoordTransform'

type TilingOptions = {
  ellipsoid?: Ellipsoid;
  numberOfLevelZeroTilesX?: number;
  numberOfLevelZeroTilesY?: number;
  rectangleSouthwestInMeters?: Cartesian2;
  rectangleNortheastInMeters?: Cartesian2;
}

class GCJ02TilingScheme extends WebMercatorTilingScheme {
  constructor(options?: TilingOptions) {
    super(options)
    this.init()
  }

  init() {
    const projection: WebMercatorProjection = new WebMercatorProjection()
    const _this: any = this
    _this.projection.project = function(cartographic: any, result: any) {
      result = CoordTransform.WGS84ToGCJ02(
        CesiumMath.toDegrees(cartographic.longitude),
        CesiumMath.toDegrees(cartographic.latitude)
      )
      result = projection.project(
        new Cartographic(
          CesiumMath.toRadians(result[0]),
          CesiumMath.toRadians(result[1])
        )
      )
      return new Cartesian2(result.x, result.y)
    }
    _this.projection.unproject = function(cartesian: any, result: any) {
      let cartographic = projection.unproject(cartesian)
      result = CoordTransform.GCJ02ToWGS84(
        CesiumMath.toDegrees(cartographic.longitude),
        CesiumMath.toDegrees(cartographic.latitude)
      )
      return new Cartographic(
        CesiumMath.toRadians(result[0]),
        CesiumMath.toRadians(result[1])
      )
    }
  }
}

export default GCJ02TilingScheme
